//
//  EFSConfigManager.m
//  EFSMobile
//
//  Created by BaHCy on 16/7/13.
//  Copyright © 2016年 Elephants Financial Service. All rights reserved.
//

#import "EFSConfigManager.h"
#import "YTXRequest.h"
//#import "EFSServiceManager.h"
#import "YSAppInfo.h"
#import "YSServiceManager.h"
NSString *const EFS_CONFIGVERSIONFILE = @"ConfigVersion.plist";
NSString *const EFS_CONFIG = @"EFSConfig.plist";

@implementation ConfigVersion

- (void)setMServiceVersion:(NSMutableArray *)mServiceVersion{
    _mServiceVersion = nil;
    _mServiceVersion = mServiceVersion;
    LGlog(@"服务器配置信息:%@",_mServiceVersion);
}

- (NSMutableArray *)mLocationVersion{
    if (!_mLocationVersion) {
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",path,EFS_CONFIGVERSIONFILE]];
        if (!dict || (![dict[@"data"] isKindOfClass:[NSArray class]])) {
            _mLocationVersion = [NSMutableArray arrayWithCapacity:1];
        }else{
            _mLocationVersion = [dict[@"data"] mutableCopy];
        }
    }
    
    LGlog(@"本地配置信息:%@",_mLocationVersion);
    return _mLocationVersion;
}

- (NSString *)updateKey {
    if (!_updateKey) {
        _updateKey = @"";
    }
    return _updateKey;
}

- (BOOL) createUpdateKey {
    __block BOOL result = NO;
    [self.mServiceVersion enumerateObjectsUsingBlock:^(NSDictionary *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *serviceKey = obj[@"key"];
        NSNumber *serviceVersion = obj[@"version"];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.key CONTAINS %@",serviceKey];
        NSNumber *locationVersion;
        if (self.mLocationVersion.count) {
            NSDictionary *filterDict = [self.mLocationVersion filteredArrayUsingPredicate:predicate].firstObject;
            locationVersion = filterDict[@"version"] ? filterDict[@"version"] : @0 ;
        }else{
            locationVersion = @0;
        }
        
        if ([serviceVersion compare:locationVersion] == NSOrderedDescending) {
            result = YES;
            if (self.updateKey.length == 0) {
                self.updateKey = serviceKey;
            }else if(self.updateKey.length > 0){
                self.updateKey = [self.updateKey stringByAppendingFormat:@".%@",serviceKey];
            }
        }
    }];
    return result;
}
@end

@interface EFSConfigManager ()

@property (nonatomic, strong) NSDictionary *mConfigDict;

@property (nonatomic, strong) NSDictionary *mVersionDict;

/** 1强制 2不强制升级 */
@property (nonatomic, assign) NSInteger forceUpdateType;

/** 是否显示升级 */
@property (nonatomic, assign) BOOL isShowUpdateVersion;

@end

@implementation EFSConfigManager

+ (nonnull instancetype) sharedManager {
    static EFSConfigManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _isShowUpdateVersion = NO;
        @weakify(self);
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] skip:1] subscribeNext:^(id x) {
            @strongify(self);
            [self showUpdateVersion];
        }];
        // 使用shared 初始化
//        [[RACObserve([EFSServiceManager sharedServiceManager],mEFSServiceType) skip:1] subscribeNext:^(id x) {
//            NSFileManager* fm = [NSFileManager defaultManager];
//            NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//            NSString *filePath = [NSString stringWithFormat:@"%@/%@",path,EFS_CONFIGVERSIONFILE];
//            [fm removeItemAtPath:filePath error:nil];
//        }];
    }
    return self;
}

+ (nonnull RACSignal *)queryConfigVersion {
    RACReplaySubject *subject = [RACReplaySubject subject];
    NSDictionary *params = @{@"platform":@"ios",
                             @"packagename":[YSAppInfo bundleId]};
    YTXRequest *request = [YTXRequest requestWithName:@"config.queryConfigVersion"];
    [request sendWithParameters:params success:^(id response) {
        
        NSLog(request.requestUrl, request.requestMethod, params,response, nil);
        [subject sendNext:response];
        [subject sendCompleted];
    } failure: ^(YTXRequest *request){
        NSError *error = [NSError errorWithDomain:@"EFS" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY:@"获取配置信息版本失败"}];
        LGlog(request.requestUrl, request.requestMethod, params, nil, error);
        [subject sendError:nil];
    }];
    return subject;
}

+ (nonnull RACSignal *)queryConfig:(NSString *)requestKey {
    RACReplaySubject *subject = [RACReplaySubject subject];
    NSDictionary *params = @{@"platform":@"ios",
                             @"key":objectOrEmptyStr(requestKey),
                             @"packagename":[YSAppInfo bundleId]};
    YTXRequest *request = [YTXRequest requestWithName:@"config.queryConfig"];
    [request sendWithParameters:params success:^(id response) {
        LGlog(request.requestUrl, request.requestMethod, params,response, nil);
        [subject sendNext:response];
        [subject sendCompleted];
    } failure: ^(YTXRequest *request){
        NSError *error = [NSError errorWithDomain:@"EFS" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY:@"获取配置信息失败"}];
        LGlog(request.requestUrl, request.requestMethod, params, nil, error);
        [subject sendError:nil];
    }];

    return subject;
}

- (void)queryVersionAction {
    
    NSDictionary *params = @{@"platform":@"ios",
                             @"packagename":[YSAppInfo bundleId],
                             @"channel":[YSAppInfo marketId]};
    
    YTXRequest *request = [YTXRequest requestWithName:@"config.queryVersion"];
    [request sendWithParameters:params success:^(id response) {
        LGlog(request.requestUrl, request.requestMethod, params,response, nil);
        NSInteger errcode = [((NSNumber *)response[@"errcode"]) integerValue];
        if (errcode == 0) {
            NSString *curver = [YSAppInfo appVersion];
            NSString *lowVew = ((NSString *)response[@"low_ver"]).description;
            NSString *newVer = ((NSString *)response[@"new_ver"]).description;
            _mVersionDict = response;
            
            if ([curver compare:lowVew options:NSNumericSearch] == NSOrderedAscending) {
                NSLog(@"当前版本比最低版本小");
                _forceUpdateType = 1;
                _isShowUpdateVersion = YES;
                return ;
            }
            
            if ([curver compare:newVer options:NSNumericSearch] == NSOrderedAscending) {
                NSLog(@"当前版本小于服务器版本");
                _forceUpdateType = 2;
                _isShowUpdateVersion = YES;
                return;
            }
        }
    } failure: ^(YTXRequest *request){
        NSError *error = [NSError errorWithDomain:@"EFS" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY:@"获取服务器版本信息失败"}];
        LGlog(request.requestUrl, request.requestMethod, params, nil, error);
    }];

}

- (void)showUpdateVersion {

    if (!_isShowUpdateVersion) return;
#ifndef WIDGET_EXTETION
    NSString *cancelStr = _forceUpdateType == 1 ? nil : @"下次再说";

    UIAlertView *showAlert = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:_mVersionDict[@"remark"] delegate:nil cancelButtonTitle:cancelStr otherButtonTitles:@"前去升级", nil];
    [showAlert show];
    [[showAlert rac_buttonClickedSignal] subscribeNext:^(NSNumber *x) {
        if (x.integerValue == 0 && _forceUpdateType == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_mVersionDict[@"url"]]];
        }
        
        if (x.integerValue == 1 && _forceUpdateType == 2) {
            _isShowUpdateVersion = NO;
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_mVersionDict[@"url"]]];
        }
        
        if (x.integerValue == 0 && _forceUpdateType == 2) {
            _isShowUpdateVersion = NO;
        }
    }];
#endif
}

/** 更新配置文件 */
- (void)updateConfig {
    [self compareConfigVersion];
}

/** 比较服务器和本地配置文件 */
- (void)compareConfigVersion {
    @weakify(self);
    [[EFSConfigManager queryConfigVersion] subscribeNext:^(NSDictionary *x) {
        @strongify(self);
        if (((NSNumber *)x[@"errcode"]).integerValue == 0) {

            if ([x[@"data"] isKindOfClass:[NSArray class]]) {
                self.mConfigVersion.mServiceVersion = [x[@"data"] mutableCopy];
            }
            
            if([self.mConfigVersion createUpdateKey]){
                [self starUpdateConfig:x];
            }
        }
    }];
}

/** 开始更新配置文件 */
- (void)starUpdateConfig:(NSDictionary *)configVersion {

//    EFSLog(@"需要升级key:%@",self.mConfigVersion.updateKey);
//    @weakify(self);
//    [[EFSConfigManager queryConfig:self.mConfigVersion.updateKey] subscribeNext:^(NSDictionary *x) {
//        @strongify(self);
//        if (((NSNumber *)x[@"errcode"]).integerValue == 0) {
//            NSMutableDictionary *locationDict = [NSMutableDictionary dictionaryWithDictionary:[self loadFileWithName:EFS_CONFIG]];
//            if (!locationDict.allKeys) {
//                [self saveFile:x withFileName:EFS_CONFIG];
//            }else{
//                [x enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//                    locationDict[key] = obj;
//                }];
//                [self saveFile:locationDict withFileName:EFS_CONFIG];
//                self.mConfigDict = locationDict;
//            }
//            
//            /** 全部配置更新完成 更新 配置信息 */
//            [self saveFile:configVersion withFileName:EFS_CONFIGVERSIONFILE];
//            
//        }
//    }];
}

- (nonnull id)configValueForKey:(nonnull NSString *)mKey withRealm:(nonnull NSString *) mRealm {
    
    mKey = [mKey stringByReplacingOccurrencesOfString:@"." withString:@"_"];
    return (!mRealm || (mRealm.length == 0)) ?  self.mConfigDict[mKey] :  self.mConfigDict[mRealm][mKey];
}

#pragma deploymate push "ignored-api-availability"
- (void)saveFile:(nonnull NSDictionary *)obj withFileName:(nonnull NSString *)fileName {
     NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
     LGlog(@"沙盒目录:%@",path);
     [obj writeToFile:[NSString stringWithFormat:@"%@/%@",path,fileName] atomically:YES];
}
#pragma deploymate pop

- (NSDictionary *)loadFileWithName:(nonnull NSString *)fileName {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",path,fileName]];
    return dict ? :@{};
}

#pragma mark - Lazy Cycle
- (ConfigVersion *)mConfigVersion {
    if (!_mConfigVersion) {
        _mConfigVersion = [[ConfigVersion alloc] init];
    }
    return _mConfigVersion;
}

- (NSDictionary *)mConfigDict{
    if (!_mConfigDict) {
        _mConfigDict  = [self loadFileWithName:EFS_CONFIG] ? [self loadFileWithName:EFS_CONFIG] : @{};
    }
    return _mConfigDict;
}
@end
